import store from '@/vuex/store'
import Vue from 'vue'
import config from '@/config/index'

function params (data) {
  return Object.keys(data).map(key => `${key}=${encodeURIComponent(data[key])}`).join('&')
}

function debounce (func, wait, immediate) {
  // 'private' variable for instance
  // The returned function will be able to reference this due to closure.
  // Each call to the returned function will share this common timer.
  var timeout
  // Calling debounce returns a new anonymous function
  return function () {
    // reference the context and args for the setTimeout function
    var context = this,
        args    = arguments
    // Should the function be called now? If immediate is true
    //   and not already in a timeout then the answer is: Yes
    var callNow = immediate && !timeout
    // This is the basic debounce behaviour where you can call this
    //   function several times, but it will only execute once
    //   [before or after imposing a delay].
    //   Each time the returned function is called, the timer starts over.
    clearTimeout(timeout)
    // Set the new timeout
    timeout = setTimeout(function () {
      // Inside the timeout function, clear the timeout variable
      // which will let the next execution run when in 'immediate' mode
      timeout = null
      // Check if the function already ran with the immediate flag
      if (!immediate) {
        // Call the original function with apply
        // apply lets you define the 'this' object as well as the arguments
        //    (both captured before setTimeout)
        func.apply(context, args)
      }
    }, wait)
    // Immediate mode and no wait timer? Execute the function..
    if (callNow) func.apply(context, args)
  }
}

// Define the debounced function
var sendLog = (function () {
  var _unique = (function () {
    /* 产生唯一标识 */
    var time = new Date().getTime() + '_',
        i    = 0
    return function () {
      return time + i++
    }
  })()
  var run = function (url, p) {
    var data = window['imgLogData'] || (window['imgLogData'] = {}),
        img  = new Image(),
        uid  = _unique()
    data[uid] = img
    /* 防止img被垃圾处理 */
    img.onload = img.onerror = function () {
      /* 成功或失败后销毁对象 */
      img.onload = img.onerror = null
      img = null
      delete data[uid]
    }
    img.src = url + '?' + params({ ...p, _cache: uid })
    // 500ms超时处理
    setTimeout(() => {
      if (img && (!img.complete || !img.naturalWidth)) {
        img.src = null
      }
    }, 500)
  }
  return run
})()

function getPageName (route) {
  return route.meta.name || route.path
}

async function saveLog (eventname, activename, entertime, staytime, eventvalue) {
  const wh = Vue.$utils.Common.getWidthHeight()
  const postData = {
    terminalId: window.TerminalId || '',  // 唯一终端标识，跨项目
    openId: store.getters.openid || '', // 微信openid
    udcId: store.state.auth.authInfo.Id || '',  // UdcId
    phone: store.state.auth.authInfo.Mobile || '',  // 手机号
    fromUdcId: store.getters.fromuid || '', // 分享来源
    prePageUrl: store.getters.preRoute.path || '',  // 来自页面url
    prePageName: getPageName(store.getters.preRoute) || '',  // 来自页面名称
    prePageSort: store.getters.preRoute.meta.sort || '',  // 来自页面深度
    pageName: getPageName(store.getters.route) || '',  // 当前页面名称
    pageUrl: store.getters.route.path || '',  // 页面地址
    pageSort: store.getters.route.meta.sort || '',  // 页面深度
    eventName: eventname || '', // 事件名称，即用户行为触发的唯一事件标记
    activeName: activename || '', // 行为名称，即用户行为触发的唯一标记（初始化/init、页面进入/goin、页面离开/goout、点击/click、输入/input、选中/selected、API接品调用/apireq、API接品响应/apirep）
    eventValue: eventvalue || '', // 事件值
    sourceId: Vue.$device.sourceID, // 来源标记，即不同终端的唯一标记（微信/WeiXin、H5/H5，微信小程序/Applet，APP/APP）
    projectCode: config.ProjectCode || '', // 项目标记
    projectName: config.ProjectName || '', // 项目名称
    trafficSource: store.getters.buriedInfo.trafficSource || '', // 流量来源
    mediumId: store.getters.buriedInfo.mediumId || '', // 媒介
    classId: store.getters.buriedInfo.classId || '', // 人群
    channelId: store.getters.buriedInfo.channelId || '', // 渠道标记
    businessCode: store.getters.businessInfo.BusinessCode || '', // BusinessCode
    applyNo: store.getters.businessInfo.ApplyNo || '',  // ApplyNo
    startTime: entertime || '', // 进入页面时间
    useTime: staytime || '', // 页面停留时间
    screenSize: wh.width + '*' + wh.height, // 页面大小
    screenDPI: window.devicePixelRatio  // devicePixelRatio
  }
  try {
    if (process.env.VUE_APP_CURRENTMODE !== 'development') {
      // 生产环境
      if (config.Buried) {
        // 测试环境
        if (process.env.VUE_APP_CURRENTMODE === 'testing') {
          sendLog('/proxy/superApi/dev/pagelogs/record', postData)
        } else {
          sendLog('/proxy/superApi/pagelogs/record', postData)
        }
      }
    } else {
      // console.log('postData:', postData)
      // sendLog('/superApi/pagelogs/record', postData)
    }
  } catch (error) {
    console.log('error:', error)
  }
}

const debouncedLog = debounce((eventname, activename, eventvalue) => {
  saveLog(eventname, activename, null, null, eventvalue)
}, 300)
export default {
  appSave (eventname, activename, eventvalue, entertime, staytime) {
    saveLog(eventname || getPageName(store.getters.route) + '-页面进入', activename || 'click', entertime, staytime, eventvalue)
  },
  debounceAppSave (eventname, activename, eventvalue) {
    debouncedLog(eventname, activename, eventvalue)
  },
  saveRouteLeave () {
    // 记录离开时间
    const stay = new Date().getTime() - store.state.global.enterTime
    saveLog(getPageName(store.getters.route) + '-页面离开', 'goout', store.state.global.enterTime, stay)
  }
}
